//
//  ESMainNetTask.m
//  EasyStyle
//
//  Created by FK on 16/1/20.
//  Copyright © 2016年 FK. All rights reserved.
//

#import "ESMainNetTaskManager.h"
#import "ESNetRequestWork.h"
#import "ESMainCardDAO.h"


#import "ESWeatherNetResult.h"
#import "ESNewsWordsNetResult.h"
#import "ESNewsWordsDetailNetResult.h"
#import "ESTrainStationNetResult.h"
#import "ESJokesNetResult.h"

@implementation ESMainNetTaskManager
#pragma mark -- 开始网络请求
- (void)startNetRequestWithURL:(NSString *)url andParamDict:(NSDictionary *)paramDict andReturnBlock:(void (^)(id returnValue))reBlock
{
   
    [ESNetRequestWork NetRequestGETWithRequestURL:url
                                    WithParameter:paramDict
                             WithReturnValeuBlock:^(id returnValue) {
#if DEBUG
                                 NSString *result  = [[NSString alloc] initWithData:returnValue encoding:NSUTF8StringEncoding];
                                 NSLog(@"--------%@", result);
#endif
                                 if (reBlock) {
                                     reBlock(returnValue);
                                 }
                             } WithFailureBlock:^{
                                 [self netFailure];
                             }];
}

#pragma mark -- 天气预报
- (void)loadCardWeatherData
{
    ESDataController *shareInstance = [ESDataController shareInstance];
    NSString *cityName = [shareInstance getUserCityName];
    
    NSDictionary *paramDict = @{@"key":WeatherForecast_AppKey,@"cityname":cityName};
    
    [self startNetRequestWithURL:WeatherForecast_URL andParamDict:paramDict andReturnBlock:^(id returnValue) {
        ESWeatherNetResult *netResult = [ESWeatherNetResult new];
        
        if ([netResult respondsToSelector:@selector(parseNetResult:)]) {

            NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:returnValue options:NSJSONReadingAllowFragments error:nil];
            [netResult parseNetResult:jsonDictionary];
            
            if ([netResult.errorCode intValue] == 0) {
                
//                NSDictionary *dict = [self parseWeatherDataWithResultData:jsonDictionary];
                
                ESMainCardDAO *dao = [ESMainCardDAO shareInstance];
                [dao insertWeatherData:netResult.resultDict];
                
                self.returnBlock(netResult.resultDict);
            } else {
                [self errorCodeWithDic:netResult.reason];
            }
        }

    }];
}




#pragma mark -- 星座运势
- (ESHoroscopeNetResult *)loadCardHoroscopeDataWithUpdate:(BOOL)isUpdate andHoroscopeType:(NSString *)horoscopeType
{
    NSDictionary *horoscopeJsonDict = nil;
    ESHoroscopeNetResult *horoscopeNetResult = nil;
    
    /// 非更新状态 先使用上次缓存的数据  否则直接获取新数据
    if (!isUpdate) {
        horoscopeJsonDict = [[ESMainCardDAO shareInstance] queryHoroscopeDataWithType:horoscopeType];
        if (horoscopeJsonDict != nil) {
            horoscopeNetResult = [ESHoroscopeNetResult new];
            [horoscopeNetResult parseNetResult:horoscopeJsonDict];
        }
    }
    
    /// 若没有缓存 则请求网络获取数据
    if (horoscopeJsonDict == nil || horoscopeNetResult == nil) {
        ESDataController *shareInstance = [ESDataController shareInstance];
        NSString *consName = [shareInstance getHoroscopeConsName];
        
        /// 设置请求参数
        NSDictionary *paramDict = @{@"key":Horoscope_AppKey,@"consName":consName,@"type":horoscopeType};
        
        [self startNetRequestWithURL:Horoscope_URL andParamDict:paramDict andReturnBlock:^(id returnValue) {
            ESHoroscopeNetResult *netResult = [ESHoroscopeNetResult new];
            
            if ([netResult respondsToSelector:@selector(parseNetResult:)]) {
                
                NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:returnValue options:NSJSONReadingAllowFragments error:nil];
                
                [netResult parseNetResult:jsonDictionary];
                
                if ([netResult.errorCode intValue] == 0) {
                    
                    NSDictionary *insertDict = @{horoscopeType:jsonDictionary};;
                    
                    ESMainCardDAO *dao = [ESMainCardDAO shareInstance];
                    [dao insertHoroscopeData:insertDict];
                    
                    self.returnBlock(jsonDictionary);
                } else {
                    [self errorCodeWithDic:netResult.reason];
                }
            }
        }];
        return nil;
    }
    return horoscopeNetResult;
}

#pragma mark -- 新闻热词
- (void)loadCardNewsWordsData
{
     NSDictionary *paramDict = @{@"key":HourlyNews_AppKey,@"dtype":@"json"};
    
    [self startNetRequestWithURL:HourlyNews_Words_URL andParamDict:paramDict andReturnBlock:^(id returnValue) {
        ESNewsWordsNetResult *netResult = [ESNewsWordsNetResult new];
        
        if ([netResult respondsToSelector:@selector(parseNetResult:)]) {
            NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:returnValue options:NSJSONReadingAllowFragments error:nil];
            
            [netResult parseNetResult:jsonDictionary];
            
            if ([netResult.errorCode intValue] == 0) {
                
                ESMainCardDAO *dao = [ESMainCardDAO shareInstance];
                [dao insertNewsWordsData:netResult.wordsList];
                
                self.returnBlock(netResult.wordsList);
            } else {
                [self errorCodeWithDic:netResult.reason];
            }
        }
    }];
}

#pragma mark -- 新闻检索
- (void)loadNewsWordSearchDataWithWord:(NSString *)newsWord
{
    NSDictionary *paramDict = @{@"key":HourlyNews_AppKey,@"q":newsWord};
    
    [self startNetRequestWithURL:HourlyNews_Search_URL andParamDict:paramDict andReturnBlock:^(id returnValue) {
        ESNewsWordsDetailNetResult *netResult = [ESNewsWordsDetailNetResult new];
        
        if ([netResult respondsToSelector:@selector(parseNetResult:)]) {
            NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:returnValue options:NSJSONReadingAllowFragments error:nil];
            
            [netResult parseNetResult:jsonDictionary];
            
            if ([netResult.errorCode intValue] == 0) {
                
                self.returnBlock(netResult.newsList);
            } else {
                [self errorCodeWithDic:netResult.reason];
            }
        }
    }];
}

#pragma mark -- 最新笑话
- (void)loadCardJokesDataWithPageNum:(NSInteger)pageNum
{
    NSDictionary *paramDict = @{@"key":Jokes_AppKey,@"page":[NSNumber numberWithInteger:pageNum],@"pagesize":@10};
    
    [self startNetRequestWithURL:Jokes_Lasted_URL andParamDict:paramDict andReturnBlock:^(id returnValue) {
        ESJokesNetResult *netResult = [ESJokesNetResult new];
        
        if ([netResult respondsToSelector:@selector(parseNetResult:)]) {
            NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:returnValue options:NSJSONReadingAllowFragments error:nil];
            
            [netResult parseNetResult:jsonDictionary];
            
            if ([netResult.errorCode intValue] == 0) {
                
                ESMainCardDAO *dao = [ESMainCardDAO shareInstance];
                [dao insertLastedJokesData:netResult.jokesList];
                
                self.returnBlock(netResult.jokesList);
            } else {
                [self errorCodeWithDic:netResult.reason];
            }
        }
    }];
}


#pragma mark -- 火车站到站查询
- (void)loadCardTrainStationQueryData
{
    
    ESDataController *shareInstance = [ESDataController shareInstance];
    NSDictionary *dict = [shareInstance getTrainStationCity];
    
    NSDictionary *paramDict = @{@"key":TrainSchedule_AppKey,@"from":dict[@"departCity"],@"to":dict[@"destination"]};
    
    [self startNetRequestWithURL:TrainSchedule_Station_URL andParamDict:paramDict andReturnBlock:^(id returnValue) {
        
        ESTrainStationNetResult *netResult = [ESTrainStationNetResult new];
        
        if ([netResult respondsToSelector:@selector(parseNetResult:)]) {
            NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:returnValue options:NSJSONReadingAllowFragments error:nil];
            
            [netResult parseNetResult:jsonDictionary];
            
            if ([netResult.errorCode intValue] == 0) {
             
                self.returnBlock(netResult);
            } else {
                [self errorCodeWithDic:netResult.reason];
            }
        }
    }];
}

//#pragma 获取到正确的数据，对正确的数据进行处理
//
//
//- (void)horoscopeFetchDataSuccessWithResultData:(NSData *)resultData
//{
//    
//}

#pragma mark -- 对ErrorCode进行处理
- (void)errorCodeWithDic: (NSString *) error
{
    self.errorBlock(error);
}

#pragma mark -- 对网路异常进行处理
- (void)netFailure
{
    self.failureBlock();
}


#pragma mark -- 辅助函数


@end
